import pymysql

class db_query:
    __conn=None
    __cursor=None
    @classmethod
    def __set_conn(cls):
        if cls.__conn==None:
            cls.__conn=pymysql.connect(
                host="host",
                user="root",
                port=3306,
                database="books"
                )
            return cls.__conn
        
    @classmethod
    def __get_cursor(cls):
        if cls.__cursor==None:
            cls.__cursor=cls.__set_conn().cursor()
            return cls.__cursor

    @classmethod
    def sql_exe(cls,sql):
        try:
            cursor=cls.__get_cursor()
            cursor.execute(sql)
            if sql.split()[0].lower()=="select":
                return cursor.fetchall()
            else:
                cls.__conn.commit()
        except Exception as e:
            cls.__conn.rollback()
            print(e)
        finally:
            if cls.__cursor:
                cls.__cursor.close()
                cls.__cursor=None
            if cls.__conn:
                cls.__conn.close()
                cls.__conn=None
            
